# 放置pytest需要用到的fixture
import pytest

from application import create_app
from application import db as database


# scope默认为'function'
@pytest.fixture(scope='session')
def app():
    app = create_app('test_settings')
    return app


# session表示该fixture作用于整个测试过程，只会在测试会话开始时创建一次
@pytest.fixture(scope='session')
def db(app, request):
    database.app = app
    # 创建测试对象需要的所有table
    database.create_all()

    # 注销方法，测试结束时会回调
    def teardown():
        database.drop_all()

    # 注册结束回调的方法
    request.addfinalizer(teardown)
    return database


# function表示该fixture表示该fixture会在每个测试方法都执行
@pytest.fixture(scope='function')
def session(db, request):
    session = db.create_scoped_session()
    db.session = session

    # 每个方法执行后执行该回调函数
    def teardown():
        session.remove()

    request.addfinalizer(teardown)
    return session
